package com.dyz.leetcode._01_array;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class _59_generateMatrix {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int startRow = 0;
        int endRow = n -1;
        int startCol = 0;
        int endCol = n-1;
        int num  = 1;

        while(startRow<=endRow && startCol<=endCol){
            //top
            for(int col = startCol; col<= endCol; col++){
                res[startRow][col]=num;
                num++;
            }
            startRow++;
            if(startRow>endRow){
                break;
            }
            //right
            for(int row = startRow; row<=endRow; row++){
                res[row][endCol]=num;
                num++;
            }
            endCol--;
            if(startCol>endCol){
                break;
            }
            //buttom
            for(int col = endCol; col>=startCol; col--){
                res[endRow][col]=num;
                num++;
            }
            endRow--;
            if(startRow>endRow){
                break;
            }
            //left
            for(int row=endRow; row>=startRow; row--){
                res[row][startCol]=num;
                num++;
            }
            startCol++;

            if(startCol>endCol){
                break;
            }
        }
        return res;
    }
    public int[][] generateMatrix1(int n) {
        int[][] res = new int[n][n];
        int[][] dirs = {{0,1},{1,0},{0,-1},{-1,0}};
        int row = 0;
        int col = 0;
        int dir = 0;
        int num=1;
        //定义填充过的格子
        boolean[][] isVisit = new boolean[n][n];
        for(int i=0; i< n*n; i++){
            res[row][col] = num;
            isVisit[row][col] = true;
            num ++;
            //下一个格子
            int nextRow = row + dirs[dir][0];
            int nextCol = col + dirs[dir][1];
            //判断格子是否超出界限
            if(nextRow<0 || nextRow>=n || nextCol<0||nextCol>=n||isVisit[nextRow][nextCol]){
                //若超出格子，需要变换dir
                dir = (dir+1) % 4;
            }
            row = row+dirs[dir][0];
            col = col +dirs[dir][1];
        }
        return res;
    }

    public static void main(String[] args) {
        int[][] ints = new _59_generateMatrix().generateMatrix(3);
        System.out.println(Arrays.toString(ints));
    }
}
